/**
 *
 *  Copyright (c) 2011, AstroDAbis
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification,
 *  are permitted provided that the following conditions are met:
 *
 *      * Redistributions of source code must retain the above copyright notice,
 *        this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above copyright notice,
 *        this list of conditions and the following disclaimer in the documentation
 *        and/or other materials provided with the distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package org.jiscinvolve.astrodabis.barberry.control.jobs;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.InputStream;

import javax.validation.Valid;

import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.BindingResult;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.context.request.WebRequest;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; 

import org.jiscinvolve.astrodabis.barberry.control.Paths;
import org.jiscinvolve.astrodabis.barberry.control.ObjectData;
import org.jiscinvolve.astrodabis.barberry.control.RequestData;
import org.jiscinvolve.astrodabis.barberry.control.BaseController;

import org.jiscinvolve.astrodabis.barberry.common.core.Tag;
import org.jiscinvolve.astrodabis.barberry.common.core.Account;

import org.jiscinvolve.astrodabis.barberry.common.core.Identifier;
import org.jiscinvolve.astrodabis.barberry.common.core.Identified;
import org.jiscinvolve.astrodabis.barberry.common.core.SimpleIdent;

import org.jiscinvolve.astrodabis.barberry.common.core.exception.*;

import org.jiscinvolve.astrodabis.barberry.common.data.TapService;
import org.jiscinvolve.astrodabis.barberry.common.data.TapTable;
import org.jiscinvolve.astrodabis.barberry.common.data.TapColumn;

import org.jiscinvolve.astrodabis.barberry.control.jobs.CreateJobBean;

import org.jiscinvolve.astrodabis.barberry.common.core.Job;
import org.jiscinvolve.astrodabis.barberry.common.core.Job.TagNameSrc;
import org.jiscinvolve.astrodabis.barberry.common.core.Job.TagDataSrc;
import org.jiscinvolve.astrodabis.barberry.common.core.Job.SourceType;
import org.jiscinvolve.astrodabis.barberry.common.core.JobRunner;

import org.jiscinvolve.astrodabis.barberry.common.inport.votable.VOTableStarTableParser;
import org.jiscinvolve.astrodabis.barberry.common.inport.startable.TaggedStarTableParser;

/**
 *
 */
@Controller
@RequestMapping(Paths.JOB_CREATE)
public class CreateJobController
extends BaseController
    {

    /**
     * Our debug logger.
     * 
     */
    private static Log log = LogFactory.getLog(CreateJobController.class);

    /**
     * Create Tag form.
     * 
     */
    public static final String FORM_PAGE = "jobs/job-create" ;

    /**
     * Form data attribute name.
     * 
     */
    public static final String FORM_DATA = "bean" ;

    /**
     * Create our RequestData for this request.
     *
     */
    @ModelAttribute(RequestData.MODEL_ATTRIB)
    public RequestData data(
        WebRequest request
        ){
        return new RequestData(
            request,
            womble,
            actor(
                request
                )
            );
        }

    /**
     * Get the form page.
     * 
     */
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView page(
	    @ModelAttribute(RequestData.MODEL_ATTRIB) RequestData data,
	    ModelAndView model
	    ){
        //
        // If we are logged in.
        if (data.actor() != null)
            {
            model.addObject(
                FORM_DATA,
                new CreateJobBean()
                );
            model.setViewName(
    		    FORM_PAGE
                );
            return model ;
            }
        //
        // If we are not logged in.
        else {
            throw new PermissionException();
            }
        }

/*
 * Upload progress bar ...
 * http://forum.springsource.org/showthread.php?32367-File-Upload-Progress-Bar
 *
 */
 
    /**
     * Post the create tag form.
     * 
     */
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView post(
	    @ModelAttribute(FORM_DATA) @Valid CreateJobBean bean, BindingResult result,
	    @ModelAttribute(RequestData.MODEL_ATTRIB) RequestData data,
	    ModelAndView model
	    ){
        Account actor = data.actor();        
        log.debug("CreateJobController.post(....)");
        log.debug(" Actor [" + ((actor != null) ? actor.ident() : null ) + "]");
        //
        // If we are not logged in.
        if (data.actor() == null)
            {
            throw new PermissionException();
            }
        //
        // If we are logged in.
        else {

//
// If name is null, use the current date.
// String name ;
// String text ;
            //
            // Try resolving the service identifiers.
            bean.resolve(
                womble
                );
            //
            // Check the primary service, table and column.
            if (bean.srvOne() == null)
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sidOne",
                        "please select a TAP service"
                        )
                    );
                }
            else if (bean.tabOne() == null)
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "tidOne",
                        "please select a table"
                        )
                    );
                }
            else if (bean.getColumnOne() == null)
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "cidOne",
                        "please select a column"
                        )
                    );
                }
            //
            // Check the associated service, table and column.
            else if ((bean.getJoined()) && (bean.srvTwo() == null))
                    {
                    result.addError(
                        new FieldError(
                            FORM_DATA,
                            "sidTwo",
                            "please select a TAP service"
                            )
                        );
                    }
            else if ((bean.getJoined()) && (bean.tabTwo() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "tidTwo",
                        "please select a table"
                        )
                    );
                }
            else if ((bean.getJoined()) && (bean.getColumnTwo() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "cidTwo",
                        "please select a column"
                        )
                    );
                }

            else if ((bean.getTagNameSrc() == TagNameSrc.INPAGE) && (bean.getTagName() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "tagName",
                        "please enter a tag name"
                        )
                    );
                }
            else if ((bean.getTagNameSrc() == TagNameSrc.INPAGE) && (bean.getTagName().isEmpty()))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "tagName",
                        "please enter a tag name"
                        )
                    );
                }
            else if ((bean.getTagNameSrc() == TagNameSrc.INPAGE) && (bean.getTagName().matches(Tag.NAME_INCLUDE) == false))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "tagName",
                        "tag names may only contain a-z, 0-9, dot '.' or dash '-'"
                        )
                    );
                }
            else if ((bean.getTagDataSrc() == TagDataSrc.INPAGE) && (bean.getTagData() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "tagData",
                        "please enter a tag value"
                        )
                    );
                }

            else if ((bean.getSourceType() == SourceType.UPLOAD) && (bean.getSourceFile() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sourceFile",
                        "please select a source file"
                        )
                    );
                }
            else if ((bean.getSourceType() == SourceType.UPLOAD) && (bean.getSourceFile().isEmpty()))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sourceFile",
                        "please select a source file"
                        )
                    );
                }

            else if ((bean.getSourceType() == SourceType.IMPORT) && (bean.getSourceUrl() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sourceFile",
                        "please enter a source URL"
                        )
                    );
                }
            else if ((bean.getSourceType() == SourceType.IMPORT) && (bean.getSourceUrl().isEmpty()))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sourceFile",
                        "please enter a source URL"
                        )
                    );
                }
/*
            else if ((bean.getSourceType() == SourceType.IMPORT) && (bean.parseSourceUrl() == null))
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sourceFile",
                        "invalid syntax for source URL"
                        )
                    );
                }
 */
            else if (bean.getSourceType() == SourceType.QUERY)
                {
                result.addError(
                    new FieldError(
                        FORM_DATA,
                        "sourceQueryText",
                        "Sorry, query import not implemented yet"
                        )
                    );
                }

            //
            // If the form has validation errors, re-display the form page.
		    if (result.hasErrors())
		        {
                log.debug("Input data has errors");
                for(FieldError error : result.getFieldErrors())
                    {
                    log.debug("  Error [" + error.getObjectName() + "][" + error.getField() + "][" + error.getDefaultMessage() + "]");
                    }
        		model.setViewName(
                    FORM_PAGE
                    );
		        }
            else {
                log.debug("Input data validated :-)");

                try {

                    //
                    // Create our job.
log.debug("JOB Creating job");
                    Job job = actor.jobs().create(
                        bean
                        );
                    //
                    // Wrap it up with data source parser.
log.debug("JOB Getting stream");
InputStream stream = bean.getSourceFile().getInputStream();

log.debug("JOB Creating parser");
                    Runnable runner = new JobRunner(
                        new TaggedStarTableParser(
                            job,
                            new VOTableStarTableParser(
                                stream
                                )
                            )
                        );
                    //
                    // Run the job in current thread ...
log.debug("JOB Running job");
                    runner.run();
                    //
                    // Re-direct to the details page.
log.debug("JOB Redirect ..");
            		model.setViewName(
                        data.redirect(
                            job
                            )
                        );
                    }
                catch (Exception ouch)
                    {
                    log.warn("Exception during job processing [" + ouch.getMessage() + "]");
                    }

		        }
            }
        return model ;
        }

    }

